package com.lagou.work1;

import org.apache.flink.api.common.functions.FlatMapFunction;

import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/*
    flink入门案例 wordcount 批处理java版
 */
public class WordCountJavaBatch {
    public static void main(String[] args) throws Exception {
        //定义输入输出文件
        String in = "src/main/java/com/lagou/work1/wc.txt";
        String out = "src/main/java/com/lagou/work1/out";

        //获取flink 执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //获取文件内容
        DataSource<String> text = env.readTextFile(in);
        //对文件进行处理
        FlatMapOperator<String,Tuple2<String,Integer>> data = text.flatMap(new SplitClz());
        //聚合相同单词
        UnsortedGrouping<Tuple2<String, Integer>> grouping = data.groupBy(0);
        //累加相同单词出现次数
        AggregateOperator<Tuple2<String,Integer>> operator = grouping.sum(1);
        //保存输出结果
        operator.writeAsText(out).setParallelism(1);
        operator.print();
        //env.execute();
    }
    //对数据进行切分，拼接处理
    private static class SplitClz implements FlatMapFunction<String, Tuple2<String,Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] s1 = s.split(" ");
            for(String word : s1) {
                collector.collect(new Tuple2<String, Integer>(word,1));
            }
        }
    }
}

